<?php
declare(strict_types=1);
/**
 * @project: 兔兔找图微信小程序
 * @author: kert
 * @date: 2023/5/16
 * @link: http://www.tiku-cloud.com/
 * @site: 微信搜索-兔兔找图
 */

namespace App\Library\Ai\BaiDu;

use App\Exceptions\AiException;
use App\Library\SnowFlakeId;
use Illuminate\Support\Facades\Storage;

class BaiDuApiImage extends ApiBase
{
    /**
     * 人物转漫画头像
     * @param string $imageUrl 原图片地址
     * @param string $artistValue 图片风格
     * @param int $maskId 口罩指数
     * @return array
     * @throws AiException
     */
    public function imageProcess(string $imageUrl, string $artistValue = "anime", int $maskId = 1): array
    {
        $token = $this->accessToken;
        $url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=' . $token;
        if ($artistValue == "anime") {
            $res = $this->requestPost($url, [
                "url" => $imageUrl
            ]);
        } else {
            $res = $this->requestPost($url, [
                "url" => $imageUrl,
                "type" => $artistValue,
                "mask_id" => $maskId
            ]);
        }
        if (isset($res["error_code"])) {
            return [
                "code" => 1,
                "msg" => $res["error_msg"],
            ];
        }
        $fileName = SnowFlakeId::getId() . ".png";
        $downloadFile = Storage::disk("public_disk")->put($fileName, base64_decode($res["image"]));
        if ($downloadFile) {
            return [
                "url" => config("app.url") . Storage::url($fileName),
                "msg" => "图片生成成功",
                "code" => 0,
            ];
        }
        return [
            "code" => 2,
            "msg" => "文件存储失败",
        ];
    }

    /**
     * 通用物体和场景识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function advancedGeneral(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=' . $this->accessToken;
        $img = file_get_contents($imageUrl);
        $img = base64_encode($img);
        return $this->requestPost($url, [
            "image" => $img,
        ]);
    }


    /**
     * 通用物体和场景识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function objectDetect(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=' . $this->accessToken;
        $img = file_get_contents($imageUrl);
        $img = base64_encode($img);
        return $this->requestPost($url, [
            "image" => $img,
        ]);
    }

    /**
     * 动物识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function animal(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=' . $this->accessToken;
        $resultArray = $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
        if (isset($resultArray["result"]) && count($resultArray["result"]) > 0) {
            $animalList = [];
            foreach ($resultArray["result"] as $value) {
                $animalList[] = [
                    ["key" => "动物名称", "value" => $value["name"]],
                    ["key" => "识别相识度", "value" => $value["score"]]
                ];
            }
            return $animalList;
        }
        return [];
    }

    /**
     * 植物识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function plant(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=' . $this->accessToken;
        $resultArray = $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
        if (isset($resultArray["result"]) && count($resultArray["result"]) > 0) {
            $plantList = [];
            foreach ($resultArray["result"] as $value) {
                $plantList[] = [
                    ["key" => "植物名称", "value" => $value["name"]],
                    ["key" => "识别相识度", "value" => $value["score"]]
                ];
            }
            return $plantList;
        }
        return [];
    }

    /**
     * logo识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function logo(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/logo?access_token=' . $this->accessToken;
        return $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
    }

    /**
     * 果蔬识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function ingredient(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient?access_token=' . $this->accessToken;
        $resultArray = $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
        if (isset($resultArray["result"]) && count($resultArray["result"]) > 0) {
            $ingredientList = [];
            foreach ($resultArray["result"] as $value) {
                $ingredientList[] = [
                    ["key" => "果蔬名称", "value" => $value["name"]],
                    ["key" => "识别相识度", "value" => $value["score"]]
                ];
            }
            return $ingredientList;
        }
        return [];
    }

    /**
     * 菜品识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function dish(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' . $this->accessToken;
        $resultArray = $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
        if (isset($resultArray["result"]) && count($resultArray["result"]) > 0) {
            $dishList = [];
            foreach ($resultArray["result"] as $value) {
                $dishList[] = [
                    ["key" => "菜品名称", "value" => $value["name"]],
                    ["key" => "识别相识度", "value" => $value["probability"]],
                    ["key" => "卡路里状态", "value" => isset($value["has_calorie"]) ? ($value["has_calorie"] ? "含有" : "不含有") : "无法识别"],
                    ["key" => "卡路里值", "value" => isset($value["calorie"]) ? $value["calorie"] : "无法识别"]
                ];
            }
            return $dishList;
        }
        return [];
    }

    /**
     * 红酒识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function redwine(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/redwine?access_token=' . $this->accessToken;
        $resultArray = $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
        if (isset($resultArray["result"]) && count($resultArray["result"]) > 0) {
            $dishList = [];
            foreach ($resultArray["result"] as $value) {
                $dishList[] = [
                    ["key" => "中文名称", "value" => $value["wineNameCn"] ?? "无法识别"],
                    ["key" => "英文名称", "value" => $value["wineNameEn"] ?? "无法识别"],
                    ["key" => "国家中文名称", "value" => $value["countryCn"] ?? "无法识别"],
                    ["key" => "国家英文名称", "value" => $value["countryEn"] ?? "无法识别"],
                    ["key" => "产区中文名称", "value" => $value["regionCn"] ?? "无法识别"],
                    ["key" => "产区英文名称", "value" => $value["regionEn"] ?? "无法识别"],
                    ["key" => "子产区中文名称", "value" => $value["subRegionCn"] ?? "无法识别"],
                    ["key" => "子产区英文名称", "value" => $value["subRegionEn"] ?? "无法识别"],
                    ["key" => "酒庄中文名称", "value" => $value["wineryCn"] ?? "无法识别"],
                    ["key" => "酒庄英文名称", "value" => $value["wineryEn"] ?? "无法识别"],
                    ["key" => "酒类型", "value" => $value["classifyByColor"] ?? "无法识别"],
                    ["key" => "糖分类型", "value" => $value["classifyBySugar"] ?? "无法识别"],
                    ["key" => "色泽", "value" => $value["color"] ?? "无法识别"],
                    ["key" => "葡萄品种中文名", "value" => $value["grapeCn"] ?? "无法识别"],
                    ["key" => "葡萄品种英文名", "value" => $value["grapeEn"] ?? "无法识别"],
                    ["key" => "品尝温度", "value" => $value["tasteTemperature"] ?? "无法识别"],
                    ["key" => "描述", "value" => $value["description"] ?? "无法识别"],
                ];
            }
            return $dishList;
        }
        return [];
    }

    /**
     * 货币识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function currency(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/currency?access_token=' . $this->accessToken;
        $resultArray = $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
        if (isset($resultArray["result"]) && count($resultArray["result"]) > 0) {
            $currencyList = [];
            foreach ($resultArray["result"] as $value) {
                $currencyList[] = [
                    ["key" => "货币名称", "value" => $value["currencyName"] ?? "无法识别"],
                    ["key" => "货币代码", "value" => $value["currencyCode"] ?? "无法识别"],
                    ["key" => "货币面值", "value" => $value["currencyDenomination"] ?? "无法识别"],
                    ["key" => "货币年份", "value" => $value["year"] ?? "无法识别"],
                ];
            }
            return $currencyList;
        }
        return [];
    }

    /**
     * 地表识别
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function landmark(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/landmark?access_token=' . $this->accessToken;
        $resultArray = $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
        if (isset($resultArray["result"]) && count($resultArray["result"]) > 0) {
            $landmarkList = [];
            foreach ($resultArray["result"] as $value) {
                $landmarkList[] = [
                    ["key" => "地标名称", "value" => $value["landmark"] ?? "无法识别"],
                ];
            }
            return $landmarkList;
        }
        return [];
    }

    /**
     * 图像多主体检测
     * @param string $imageUrl
     * @return array
     * @throws AiException
     */
    public function multiObjectDetect(string $imageUrl): array
    {
        if (empty($imageUrl)) {
            return [];
        }
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/multi_object_detect?access_token=' . $this->accessToken;
        //$img = file_get_contents($imageUrl);
        //$img = base64_encode($img);
        return $this->requestPost($url, [
            "url" => $imageUrl,
        ]);
    }
}
